<template>
  <div class="mental-question pad">
    <div class="head">
      <span>心理健康题库管理</span>
      <el-upload
        action="#"
        :http-request="handleUpload"
        :show-file-list="false"
      >
        <el-button
          circle
          icon="el-icon-upload2"
          type="primary"
          title="上传excel"
          :loading="isUploading"
        >
        </el-button>
      </el-upload>
      <el-button
        circle
        icon="el-icon-plus"
        type="primary"
        title="添加题目"
        @click="openAddDialog"
        style="margin-left: 10px;"
      ></el-button>
      <a
        class="link-a"
        href="./excel_template/mental_question_template.xlsx"
        target="_blank"
      >
        下载Excel上传模板
        <i class="el-icon-download"></i>
      </a>
    </div>
    <div class="search m-t-b">
      <el-input placeholder="题目" @input="clearSearch"  v-model="searchTxt" clearable />
      <el-button type="primary" @click="handleSearch">
        <i class="el-icon-search"></i> 搜索
      </el-button>
    </div>
    <el-table border stripe :data="questions" class="m-t-b" v-loading="loading">
      <el-table-column fixed="left" label="题目" prop="title" width="266"></el-table-column>
      <!-- <el-table-column label="题目所属心理表" prop="psychologyTitle" width="200"></el-table-column> -->
      <el-table-column label="创建时间" prop="createDate" width="150"></el-table-column>
      <el-table-column label="最近修改时间" prop="updateDate"></el-table-column>
      <!-- <el-table-column label="a选项" prop="a"></el-table-column>
      <el-table-column label="a选项分数" prop="as"></el-table-column>
      <el-table-column label="b选项" prop="b"></el-table-column>
      <el-table-column label="b选项分数" prop="bs"></el-table-column>
      <el-table-column label="c选项" prop="c"></el-table-column>
      <el-table-column label="c选项分数" prop="cs"></el-table-column>
      <el-table-column label="d选项" prop="d"></el-table-column>
      <el-table-column label="d选项分数" prop="ds"></el-table-column>
      <el-table-column label="e选项" prop="e"></el-table-column>
      <el-table-column label="e选项分数" prop="es"></el-table-column>
      <el-table-column label="f选项" prop="f"></el-table-column>
      <el-table-column label="f选项分数" prop="fs"></el-table-column>
      <el-table-column label="j选项" prop="j"></el-table-column>
      <el-table-column label="j选项分数" prop="js"></el-table-column>
      <el-table-column label="h选项" prop="h"></el-table-column>
      <el-table-column label="h选项分数" prop="hs"></el-table-column> -->
      
      <template v-for="(item, i) in options">
        <el-table-column :label="item + '选项'" :prop="item" :key="'t' + i"></el-table-column>
        <el-table-column :label="item + '选项分数'" :prop="item + 's'" :key="'s' + i"></el-table-column>

      </template>
      <el-table-column label="是否启用" fixed="right" width="200">
        <template slot-scope="scope">
          <el-switch
            active-text="启用"
            inactive-text="禁用"
            v-model="scope.row.isEnable"
            @change="changeQuestionStatus($event, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button type="default" circle icon="el-icon-edit" @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" circle icon="el-icon-delete" @click="deleteQuestion(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex m-t-b"
      :page-size="pageSize"
      :current-page="curPage"
      layout="prev, pager, next"
      @current-change="handlePagi"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog">
      <el-form :model="question" ref="question" :rules="rules" label-position="top">
        <!-- <el-form-item label="所属心理表" prop="psychologyTitleId">
          <el-select v-model="question.psychologyTitleId">
            <el-option v-for="(item, i) in mentals" :key="i" :value="item.psychologyTitleId" :label="item.psychologyTitle"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="题目" prop="title">
          <el-input v-model="question.title" />
        </el-form-item>
        <el-form-item v-for="(item, i) in answerNum" :key="i" :label="`${options[i]}选项设置`">
          <div class="flex" style="padding: 8px 0">
            <el-input v-model="question[options[i]]" placeholder="题目" style="margin-right: 4px" />
            <el-input-number
              v-model="question[options[i] + 's']"
            >
            </el-input-number>
          </div>
        </el-form-item>
        <div>
          <el-button type="primary" v-if="answerNum < options.length" size="mini" @click="addQuestionNum">添加答案</el-button>
          <el-button type="danger" v-if="answerNum > 2" size="mini" @click="reduceQuestionNum">删除答案</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" :disabled="!canUse" @click="addQuestion('question')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getMentalQuestion,
  addMentalQuestion,
  deleteMentalQuestion,
  getAllMentalChart,
  updateMentalQuestion,
  uploadMultipleQuestion
} from '../api';
import { formatDate, excel2Json } from '../util/index';
import xlsx from 'xlsx';

export default {
  name: 'MentalQuestion',
  data () {
    return {
      searchTxt:'',
      pageSize: 10,
      loading: true,
      showDialog: false,
      dialogTitle: '添加题目',
      total: 0,
      curQuestionId: '',
      canUse: true,
      curPage: 0,
      answerNum: 2,
      questions: [],
      options: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'],
      mentals: [],
      isUploading: false,
      question: {
        // psychologyTitleId: '',
        title: '',
        a: '',
        b: '',
        c: '',
        d: '',
        e: '',
        f: '',
        g: '',
        h: '',
        i: '',
        j: '',
        k: '',
        l: '',
        m: '',
        n: '',
        o: '',
        p: '',
        q: '',
        r: '',
        s: '',
        t: '',
        as: '',
        bs: '',
        cs: '',
        ds: '',
        es: '',
        fs: '',
        gs: '',
        hs: '',
        is: '',
        js: '',
        ks: '',
        ls: '',
        ms: '',
        ns: '',
        os: '',
        ps: '',
        qs: '',
        rs: '',
        ss: '',
        ts: '',
        enable: 1
      },
      rules: {
        title: [
          { required: true, message: '题目不能为空!', trigger: 'blur' }
        ],
        psychologyTitleId: [
          { required: true, message: '请选择题目所属心理表', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 搜索
    handleSearch (){
      if (!this.$checkAuth('canSearch')) {
        return this.$message.error('暂无对应操作权限!')
      };
      if (!this.searchTxt.trim()) {
        this.searchTxt = ''
        return this.$message.error('请输入搜索内容!')
      }
      this.fetchMentalQuestion(1, this.searchTxt)
    },
    handleUpload ({ file }) { // 处理上传过程
      this.isUploading = true;
      const _this = this;
      excel2Json(file, xlsx, function (work, list) {
        if (!list.length) {
          _this.isUploading = false;
          return _this.$message.error('暂无可上传题目数据')
        };
        if (!list[0].title) {
          _this.isUploading = false;
          return _this.$message.error('数据格式错误, 请检查所传表格')
        };
        list.forEach(item => {
          item.a = item.a || '';
          item.b = item.b || '';
          item.c = item.c || '';
          item.d = item.d || '';
          item.e = item.e || '';
          item.f = item.f || '';
          item.j = item.j || '';
          item.h = item.h || '';
          item.as = item.as || '';
          item.bs = item.bs || '';
          item.cs = item.cs || '';
          item.ds = item.ds || '';
          item.es = item.es || '';
          item.fs = item.fs || '';
          item.js = item.js || '';
          item.hs = item.hs || '';
          item.enable = 1
        });
        uploadMultipleQuestion(list)
        .then(res => {
          if (res.data.code === 1) {
            _this.$message.success('添加成功!');
            _this.fetchMentalQuestion(1)
          } else {
            _this.$message.error(res.data.msg || '服务异常!')
          };
          _this.isUploading = false;
        })
        .catch(e => {
          _this.isUploading = false;
          _this.$message.error('服务异常!')
        })
      })
    },
    clearSearch () {
      if (!this.searchTxt) {
        this.fetchMentalQuestion(1)
      }
    },
    fetchMentalQuestion (index,title) { // 获取心理健康测试题目
      this.loading = true;
      title = title || null;
      getMentalQuestion({
        index,
        count: this.pageSize,
        queryParam: {
          title: title,
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.total = res.data.data.totalRecord || 0;
          this.questions = list.map(item => {
            item.createDate = formatDate(item.createDate, 'ZH');
            item.updateDate = item.updateDate ? formatDate(item.updateDate, 'ZH') : '无';
            item.isEnable = item.enable ? true : false
            return item
          })
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        };
        this.loading = false
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('网络异常!')
      })
    },
    fetchAllMentalList () { // 查询所有心理健康测试表
      getAllMentalChart()
      .then(res => {
        if (res.data.code === 1) {
          this.mentals = res.data.data || [];
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    handlePagi (page) { // 分页
      this.curPage = page;
      // this.fetchMentalQuestion(page)
      if (this.searchTxt.trim()) {
        this.fetchMentalQuestion(page, this.searchTxt)
      } else {
        this.fetchMentalQuestion(page)
      }
    },
    openAddDialog () {
      if (!this.$checkAuth('canAddMentalQuestion')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.answerNum = 2;
      // this.question.psychologyTitleId = '';
      this.question.title = '';
      this.question.a = '';
      this.question.b = '';
      this.question.c = '';
      this.question.d = '';
      this.question.e = '';
      this.question.f = '';
      this.question.j = '';
      this.question.h = '';
      this.question.as = '';
      this.question.bs = '';
      this.question.cs = '';
      this.question.ds = '';
      this.question.es = '';
      this.question.fs = '';
      this.question.js = '';
      this.question.hs = '';
      this.dialogTitle = '添加题目';
      this.showDialog = true
    },
    hideDialog () {
      this.showDialog = false
    },
    addQuestionNum () { // 添加答案设置
      this.answerNum ++
    },
    reduceQuestionNum () { // 减少答案设置
      let num = this.answerNum;
      this.answerNum --;
      this.question[this.options[num - 1]] = '';
      this.question[this.options[num - 1] + 's'] = ''
    },
    addQuestion (name) {
      this.canUse = false;
      this.$refs[name].validate(valid => {
        if (valid) {
          for (let i = 0; i < this.answerNum; i ++) {
            if (!this.question[this.options[i]].trim()) {
              this.canUse = true;
              return this.$message.error('请完善答案设置')
            }
          };
          if (this.dialogTitle === '添加题目') {
            console.log(this.question);
            addMentalQuestion(this.question)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.showDialog = false;
                this.fetchMentalQuestion(1);
                this.canUse = true;
              } else {
                this.canUse = true;
                this.$message.error('网络异常!')
              }
            })
            .catch(e => {
              this.canUse = true;
              this.$message.error('网络异常!')
            })
          } else {
            updateMentalQuestion({
              id: this.curQuestionId,
              ...this.question
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showDialog = false;
                this.fetchMentalQuestion(1);
                this.canUse = true;
              } else {
                this.canUse = true;
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.canUse = true;
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    deleteQuestion (row) {
      if (!this.$checkAuth('canDeleteMentalQuestion')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row.id)
        deleteMentalQuestion(row.id)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchMentalQuestion(1)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    openEditDialog (row) {
      if (!this.$checkAuth('canEditMentalQuestion')) {
        return this.$message.error('暂无对应操作权限!')
      };
      let num = 0;
      this.options.forEach(item => {
        if (row[item]) {
          num ++
        }
      });
      this.answerNum = num;
      this.curQuestionId = row.id;
      // this.question.psychologyTitleId = row.psychologyTitleId;
      this.question.title = row.title;
      this.question.a = row.a;
      this.question.b = row.b;
      this.question.c = row.c;
      this.question.d = row.d;
      this.question.e = row.e;
      this.question.f = row.f;
      this.question.j = row.j;
      this.question.h = row.h;
      this.question.as = row.as;
      this.question.bs = row.bs;
      this.question.cs = row.cs;
      this.question.ds = row.ds;
      this.question.es = row.es;
      this.question.fs = row.fs;
      this.question.js = row.js;
      this.question.hs = row.hs;
      this.question.enable = row.enable;
      this.dialogTitle = '修改题目';
      this.showDialog = true
    },
    changeQuestionStatus (e, data) { // 更改心理题目是否启用
      if (!this.$checkAuth('canSetMentalQuestionStatus')) {
        data.isEnable = !e;
        return this.$message.error('暂无对应操作权限!')
      };
      this.$confirm(`确定${e ? '启用' : '禁用'}此问题吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        data.enable = data.isEnable ? 1 : 0;
        updateMentalQuestion({
          id: data.id,
          // psychologyTitleId: data.psychologyTitleId,
          title: data.title,
          a: data.a,
          b: data.b,
          c: data.c,
          d: data.d,
          e: data.e,
          f: data.f,
          j: data.j,
          h: data.h,
          as: data.as,
          bs: data.bs,
          cs: data.cs,
          ds: data.ds,
          es: data.es,
          fs: data.fs,
          js: data.js,
          hs: data.hs,
          enable: data.enable
        })
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.fetchMentalQuestion(this.curPage);
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      })
      .catch(error => {
        data.isEnable = !e;
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    }
  },
  created () {
    this.fetchMentalQuestion(1);
    this.fetchAllMentalList()
  }
}
</script>
<style lang="scss">
  .mental-question {
    .link-a {
      cursor: pointer;
      margin-left: 5px;
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
  .search{
    // border:1px solid saddlebrown;
    // padding-left:50px;
  }
  .searchinput{
    width:200px;
  }
  .mental-question {
    .search {
      display: flex;
    }
    table {
      .cell {
        text-align: center;
      }
    }
  }
</style>
